package com.yenlien.traceyun.business.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.dao.*;
import com.yenlien.traceyun.business.entity.*;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.trace.TraceInfo;
import com.yenlien.traceyun.business.trace.TraceService;
import com.yenlien.traceyun.common.utils.Tools;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-11-30
 * @description: 种植分包
 **/

@Service
public class PlantSubPackService {

    @Autowired
    private ProcessDetailDao processDetailDao;

    @Autowired
    private StorageManageDao storageManageDao;

    @Autowired
    private StorageManageDetailedDao storageManageDetailedDao;

    @Autowired
    private SubpackageDao subpackageDao;

    @Autowired
    private TraceService traceService;

    @Autowired
    private ProcessMaterialDao processMaterialDao;

    @Autowired
    private ProcessMaterialsDao processMaterialsDao;

    @Autowired
    private ProduceManageDao produceManageDao;

    @Autowired
    private BoxDao boxDao;

    @Value("${traceyun.app.id}")
    private String appId;

    @Transactional(rollbackFor = RuntimeException.class)
    public Subpackage save(Subpackage subpackage) {
        subpackage.setAppId(appId);
        String source = subpackage.getSource();
        if (subpackage.getIsOk() == 1) {
            subpackage.setTotalNumber((int) Math.ceil(subpackage.getSubNumber() * 1.05));
        } else {
            subpackage.setTotalNumber(subpackage.getSubNumber());
        }

        if (("生产分包").equals(source)) {
            ProcessDetail processDetail = processDetailDao.findById(subpackage.getRelevanceId());

            if(StringUtils.isBlank(subpackage.getType())){
                // 新加
                ProduceManage produceManage;
                if (processDetail == null) {
                    produceManage = produceManageDao.findById(subpackage.getRelevanceId());
                    processDetail = processDetailDao.findProcessId(produceManage.getId());
                } else {
                    produceManage = produceManageDao.findById(processDetail.getProcessId());
                }
                String subtr = Tools.subtr(processDetail.getSurplusNumber(), subpackage.getWeight());
                if (new BigDecimal(subtr).compareTo(new BigDecimal("0")) == -1) {
                    throw new BusinessException("数量不能大于剩余量");
                }
                produceManage.setSurplusNumber(subtr);
                produceManage.setSubNumber(subpackage.getSubNumber());
                produceManage.setBranchPackageNum(subpackage.getBranchPackageNum());
                produceManage.setIsOk(subpackage.getIsOk());
                produceManage.setWeight(subpackage.getWeight());
                produceManage.setPrintNumber(subpackage.getPrintNumber());
                produceManage.setTypes(subpackage.getTypes());
                // 新加结束
                produceManageDao.save(produceManage);
            }

            processDetail.setSurplusNumber(Tools.subtr(processDetail.getSurplusNumber(), subpackage.getWeight()));
            processDetail.setSpec(subpackage.getSpec());
            processDetail.setSpecUnits(subpackage.getSpecUnits());
            processDetailDao.save(processDetail);

            subpackage.setProductName(processDetail.getProductName());
//            subpackage.setBatch(processDetail.getBatch());
            subpackage.setGrade(processDetail.getGrade());
            subpackage.setLastStep(subpackage.getRelevanceId());
            System.out.println("追溯码数量：" + subpackage.getSubNumber() + "分包数：" + subpackage.getBranchPackageNum());
            if (subpackage.getSubNumber() > subpackage.getBranchPackageNum()) {
                System.out.println("追溯码数量：" + subpackage.getSubNumber() + "分包数：" + subpackage.getBranchPackageNum());
                throw new BusinessException("403", "追溯码数量不能大于分包数量");
            }
            if (subpackage.getBatch() == null) {
                subpackage.setBatch(String.valueOf(System.currentTimeMillis()));
            }
            subpackageDao.save(subpackage);

//            saveBatchCode(subpackage);          //将分包的个数入库t_plant_box
//            traceService.addInfo(subpackage.getBatch(), subpackage, appId, UserAuthUtil.getLoginUser().getCompanyId());
            generateTraceInfo(subpackage, processDetail.getId());

        } else if (("采购分包").equals(source)) {
            StorageManage storageManage = storageManageDao.findById(subpackage.getRelevanceId());
            String weight = subpackage.getWeight();
            String bag = Tools.division(weight, storageManage.getSpecs().toString());

//            storageManage.setSubtotal(Tools.subtr(storageManage.getSubtotal(), weight));
//            storageManage.setSurplus(Tools.subtr(storageManage.getSurplus(), bag));
            storageManageDao.save(storageManage);

            StorageManageDetailed storageManageDetailed = new StorageManageDetailed();
            storageManageDetailed.setStorageManageId(storageManage.getId());
            storageManageDetailed.setType("分包");
            storageManageDetailed.setSpecs(storageManage.getSpecs());
//            storageManageDetailed.setNumber(bag);
            storageManageDetailedDao.save(storageManageDetailed);

            subpackage.setProductName(storageManage.getProductName());
//            subpackage.setBatch(storageManage.getBatch());
            subpackage.setGrade(storageManage.getSupplierName());
            subpackage.setLastStep(subpackage.getRelevanceId());
            System.out.println("追溯码数量：" + subpackage.getSubNumber() + "分包数：" + subpackage.getBranchPackageNum());
            if (subpackage.getSubNumber() > subpackage.getBranchPackageNum()) {
                System.out.println("追溯码数量：" + subpackage.getSubNumber() + "分包数：" + subpackage.getBranchPackageNum());
                throw new BusinessException("403", "追溯码数量不能大于分包数量");
            }
            if (subpackage.getBatch() == null) {        //H5页面没有自动生成批次号
                subpackage.setBatch(String.valueOf(System.currentTimeMillis()));
            }
            subpackageDao.save(subpackage);

//            saveBatchCode(subpackage);          //将分包的个数入库t_plant_box

            CodeInfo p = new CodeInfo();
            p.setAppId(appId);
            p.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
            p.setCode(storageManage.getBatch());
            p.setBatchNo(storageManage.getBatch());
            p.setCreatetime(new Date());
            TraceInfo traceInfo = new TraceInfo();
            traceInfo.setStep("storageManage");
            traceInfo.setInfo(storageManage);
            List<TraceInfo> children = new ArrayList<>();
            TraceInfo child = new TraceInfo();
            child.setStep("storageManageDetailed");
            List<StorageManageDetailed> detaileds = storageManageDetailedDao.findByStorageManageId(storageManage.getId());
            child.setInfo(detaileds);
            children.add(child);
            traceInfo.setChildren(children);
            p.setContent(JSONObject.toJSONString(traceInfo));
            traceService.addCodeInfo(p);
        }
        return subpackage;

    }
        // 2022-6-2 原
    private void generateTraceInfo(Subpackage subpackage, String processDetailId) {
        ProcessDetail processDetail = processDetailDao.findById(subpackage.getRelevanceId());
        if (processDetail == null) {
            processDetail = processDetailDao.findById(processDetailId);
        }
        List<ProcessMaterial> materialList = processMaterialDao.findByProcessId(processDetail.getProcessId());
        for (ProcessMaterial material : materialList) {
            processDetail.setLastStep(material.getId());
            traceService.addInfo(subpackage.getBatch(), material.getBatch(), subpackage, appId, UserAuthUtil.getLoginUser().getCompanyId(), "processMaterial");
        }
    }

//    private void generateTraceInfo(Subpackage subpackage, String processDetailId) {
//        ProcessDetail processDetail = processDetailDao.findById(subpackage.getRelevanceId());
//        if (processDetail == null) {
//            processDetail = processDetailDao.findById(processDetailId);
//        }
//        List<ProcessMaterial> materialList = processMaterialDao.findByProcessId(processDetail.getProcessId());
//        if(CollectionUtils.isEmpty(materialList)){
//            List<ProcessMaterials> materialsList = processMaterialsDao.findByProcessPlanId(processDetail.getProcessPlanId());
//            for (ProcessMaterials material : materialsList) {
//                processDetail.setLastStep(material.getId());
//                traceService.addInfo(subpackage.getBatch(), material.getMaterialBatch(), subpackage, appId, UserAuthUtil.getLoginUser().getCompanyId(), "processMaterials");
//            }
//        }else {
//            for (ProcessMaterial material : materialList) {
//                processDetail.setLastStep(material.getId());
//                traceService.addInfo(subpackage.getBatch(), material.getBatch(), subpackage, appId, UserAuthUtil.getLoginUser().getCompanyId(), "processMaterial");
//            }
//        }
//    }


    //批次号入库，统计未打码数
    public void saveBatchCode(Subpackage subpackage) {
        //批次号存入t_plant_box表
        int num = subpackage.getSubNumber();
        List<Box> boxes = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Box box = new Box();
            box.setSubpackageBatch(subpackage.getBatch());
            box.setCreatetime(new Date());
            box.setSubpackageId(subpackage.getId());
            box.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
            box.setActivation(false);
            box.setAppId(appId);
            boxes.add(box);
        }
        boxDao.saveAll(boxes);
    }
}
